package ru.spb.osll.myfit.server.parser;

import java.util.LinkedList;
import java.util.List;

import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.WikiText;
import ru.spb.osll.myfit.server.Converter;
import ru.spb.osll.myfit.util.StringUtils;

public class WikiElementParser implements IAccumulatingParser {

  private Converter m_converter;
  private List<String> m_textLines = new LinkedList<String>(); 
  
  public WikiElementParser(Converter converter) {
    m_converter = converter;
  }
  
  @Override
  public PageElement reset() {
    if(m_textLines.isEmpty()){
      return null;
    }
    WikiText wikiText = createWikitext();
    m_textLines.clear();
    return wikiText;
  }

  @Override
  public boolean matches(String line) {
    return true;
  }

  @Override
  public PageElement parse(String line) {
    String newLine = line.trim();
    m_textLines.add(newLine);
    return null;
  }
  
  private WikiText createWikitext(){
    String separator = System.getProperty("line.separator");
    String wiki = StringUtils.join(m_textLines, separator).trim();
    if(wiki.isEmpty()){
      return null;
    }
    String htmlText = m_converter.convertWikiToHtml(wiki);
    WikiText wikiText = new WikiText(wiki, htmlText);
    return wikiText;
  }
}
